package com.sptpc.hello.service.impl;

import com.sptpc.hello.modei.Category;
import com.sptpc.hello.modei.Drink;
import com.sptpc.hello.repository.CategoryRepository;
import com.sptpc.hello.repository.DrinkRepository;
import com.sptpc.hello.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CategoryJpaService implements ICategoryService {
    @Autowired
    public CategoryRepository categoryRepository;
    @Autowired
    private DrinkRepository drinkRepository;

    @Override
    public List<Category> getAllCategories() {

        return categoryRepository.findAll();
    }

    @Override
    public void addNewCategory(Category category) {
        categoryRepository.save(category);
    }

    @Override
    public Category getCategoryById(Integer id) {
        return categoryRepository.findById(id).orElse(null);
    }

    @Override
    public void updateCategory(Category category) {
        categoryRepository.save(category);
    }

    @Override
    public void deleteCategoryById(Integer id) {

        //2、更新所有和该category关联的drink
        //2.1 通过category_id把关联的drink查询出来
        List<Drink> drinks = drinkRepository.findDrinksByCategory_Id(id);

        for (Drink drink : drinks) {
            //2.2 把这些drink的category设置为空
            drink.setCategory(null);
            //2.3 保存
            drinkRepository.save(drink);
        }
        //1、删除指定ID的category
        categoryRepository.deleteById(id);


    }
}
